public class _57 {
    static class Solution {
        //这题，边界条件能把脑子烧坏
        public int[][] insert(int[][] intervals, int[] newInterval) {
            int[] merge = new int[]{newInterval[0], newInterval[1]};
            int x = -1;
            int y = -1;
            int s = newInterval[0];
            int e = newInterval[1];
            for (int i = 0; i < intervals.length; i++) {
                if (s >= intervals[i][0] && s <= intervals[i][1]) {
                    x = i;
                    merge[0] = intervals[i][0];
                } else if (s > intervals[i][1]) {
                    merge[0] = s;
                    x = i + 1;
                }
                if (e >= intervals[i][0] && e <= intervals[i][1]) {
                    merge[1] = intervals[i][1];
                    y = i;
                } else if (e > intervals[i][1]) {
                    merge[1] = e;
                    y = i;
                }
            }
            // System.out.println(String.format("x=%d,y=%d,merge[0] = %d,merge[1]=%d",x,y,merge[0],merge[1]));
            int[][] res = null;
            if (x == y && x == -1) {
                res = new int[intervals.length + 1][2];
                res[0] = newInterval;
                System.arraycopy(intervals, 0, res, 1, intervals.length);
                return res;
            } else {
                //[x,y]
                if (x == -1) {
                    res = new int[intervals.length - y][2];
                    res[0] = merge;
                    System.arraycopy(intervals, y + 1, res, 1, res.length - 1);
                } else {
                    res = new int[intervals.length - y + x][2];
                    if (x > 0) {
                        System.arraycopy(intervals, 0, res, 0, x);
                    }
                    if (y < intervals.length - 1) {
                        System.arraycopy(intervals, y + 1, res, x + 1, intervals.length - y - 1);
                    }
                    res[x] = merge;
                }
            }
            return res;

        }
    }
}
